<?php

namespace App\Trip\Orders\BookOrders\Train\SelectedSeats;

use App\Trip\Train\Seat\Seats;
use App\Trip\Train\Seat\SeatType;
use Exception;

class BuildSnapSelectedSeats extends SelectedSeats
{
    use TraitParseSelectedSeats;

    /**
     *  0 无选座 1 坐席 2 铺席
     * @var int
     */
    private int $seat_type = 0;

    /**
     * @throws Exception
     */
    public function __construct(array $selected_seats)
    {
        $this->selected_seats = $selected_seats;
        $this->buildSeatsOrderBeds();
    }

    /**
     * 解析 硬座 卧铺 靠窗等
     *
     * @throws Exception
     */
    private function buildSeatsOrderBeds(): void
    {
        $this->seat_type = 0;
        $sides           = [
            "窗"   => [
                "A",
                "F",
            ],
            "过道" => [
                "C",
                "D",
                "F",
            ],
        ];

        $bed = 0;
        foreach ($this->selected_seats as $key => $seat) {
            $seat_type       = $seat['seat_type'];
            $this->seat_type = $seat_type;
            $seat_name       = $seat['seat'];
            if ($seat_type == Seats::SEAT_TYPE_SEAT) {
                $seats = implode(",", $sides[$seat_name]);
            } else {
                $seats = collect(explode(",", $seat_name))
                    ->map(function ($name) {
                        $beds = array_flip(Seats::TRAIN_BEDS);
                        return $beds[$name];
                    })
                    ->implode(',');
                $bed++;
                if ($bed > 1) {
                    throw new Exception('参数错误');
                }
            }

            $service_fee = SeatType::selectFee($seat_type);
            if (!isset($this->build_seats[$seat['seat']])) {
                $this->build_seats[$seat['seat']] = [
                    'seat_type'   => $seat_type,
                    'seat'        => $seat['seat'],
                    'seats'       => $seats,
                    'service_fee' => $service_fee,
                    'count'       => $seat['count'] ?? 1,
                ];
            } else {
                isset($seat['count']) ? $this->build_seats[$seat['seat']]['count'] = $seat['count'] : $this->build_seats[$seat['seat']]['count']++;
            }
        }
    }

    public function __toString(): string
    {
        return json_encode($this->getSelectedSeats(), JSON_UNESCAPED_UNICODE) ?: '';
    }

    public function getSelectedSeats(): array
    {
        return $this->build_seats;
    }

    public function getSeatType(): int
    {
        return $this->seat_type;
    }
}